package com.hugesoft.jxgs.activity;

import java.util.Date;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hugesoft.jxgs.R;
import com.hugesoft.jxgs.activity.base.BaseActivity;
import com.hugesoft.jxgs.utils.CheckInputUtil;
import com.hugesoft.logic.managers.LogicManager;
import com.hugesoft.logic.managers.common.Constans;
import com.hugesoft.logic.module.DriverLicence;
import com.hugesoft.logic.module.Police;
import com.hugesoft.logic.module.Traffic;
import com.hugesoft.utils.Util;

public class TrafficActivity extends BaseActivity implements OnClickListener {
	Button mSearchDriverInfo, mSearchPoliceInfo, mTakePic, mBtnSubmit,
			mBtnSignature;
	TextView tvPlateNumber, tvDriverType, tvDriverName, tvDriverAge,
			tvPoliceName, tvPoliceNo;
	EditText etStart, etEnd, etDriverLicenceNo, etDriverTime, etTel,
			etPermittedWeight, etRealWeight, etSafeMethod, etPermittedGoods;
	RadioButton rbtnYearChecked, rbtnNoYearChecked;
	RadioButton rbtnSafeDeviceReady, rbtnNoSafeDeviceReady;
	RadioButton rbtnWheelBroken, rbtnNoWheelBroken;

	public static int REQUESTCODE_ADDLICENCE = 1000;
	public static int REQUESTCODE_SEARCHPOLICE = REQUESTCODE_ADDLICENCE + 1;
	public static int REQUESTCODE_CAPTURE = REQUESTCODE_SEARCHPOLICE + 1;
	public static int REQUESTCODE_SIGNATURE = REQUESTCODE_CAPTURE + 1;
	private Traffic mTrafficInfo = new Traffic();
	private static String TAG = "TrafficActivity";

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			dismissDialog();
			switch (msg.what) {
			case Constans.ADD_TRAFFIC_SUCCESS:
				// 登录成功，摘取该用户的信息
				Toast.makeText(TrafficActivity.this, "上传成功", Toast.LENGTH_LONG)
						.show();
				Intent intent = new Intent();
				intent.putExtra(Constans.TAGPLATENUMBER,
						mTrafficInfo.getPlatenumber());
				setResult(0, intent);
				finish();
				break;
			case Constans.ADD_TRAFFIC_FAILED:
				Toast.makeText(TrafficActivity.this,
						msg.obj == null ? "上传失败" : msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Long trafficid = getIntent().getLongExtra(Constans.TAGTRAFFICID, 0);
		Traffic tmptrafficInfo = LogicManager.trafficManager().loadtrafficinfo(
				trafficid);
		initUI();
		if (tmptrafficInfo == null) {
			String platenumber = getIntent().getStringExtra(
					Constans.TAGPLATENUMBER);
			if (platenumber != null) {
				tvPlateNumber.setText(platenumber);
			}
			mTrafficInfo.setPlatenumber(platenumber);
			mTrafficInfo.setPoliceid(LogicManager.policeManager()
					.getcurrentpolice().getId());
		} else {
			mTrafficInfo.setPlatenumber(tmptrafficInfo.getPlatenumber());
			mTrafficInfo.setStartposition(tmptrafficInfo.getStartposition());
			mTrafficInfo.setEndposition(tmptrafficInfo.getEndposition());
			mTrafficInfo.setDrivertime(tmptrafficInfo.getDrivertime());
			mTrafficInfo.setTelnum(tmptrafficInfo.getTelnum());
			mTrafficInfo.setPermittedgoods(tmptrafficInfo.getPermittedgoods());
			mTrafficInfo.setPermittedquality(tmptrafficInfo
					.getPermittedquality());
			mTrafficInfo.setActualquality(tmptrafficInfo.getActualquality());
			mTrafficInfo.setIsyearchecked(tmptrafficInfo.getIsyearchecked());
			mTrafficInfo.setIssafedeviceready(tmptrafficInfo
					.getIssafedeviceready());
			mTrafficInfo.setIswheelbroken(tmptrafficInfo.getIswheelbroken());
			mTrafficInfo.setSavemethod(tmptrafficInfo.getSavemethod());
			// 以下二项需要更新的，就不复制了
			// mTrafficInfo.setPic(tmptrafficInfo.getPic());
			// mTrafficInfo.setCheckdate(tmptrafficInfo.getCheckdate());
			setUIWithTrafficInfo();
		}
	}

	private void initUI() {
		setContentView(R.layout.activitytraffic);
		((TextView) findViewById(R.id.titleTextView)).setText("危化品车辆");
		findViewById(R.id.backImg).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		tvPlateNumber = (TextView) findViewById(R.id.tvPlateNumber);
		mSearchDriverInfo = (Button) findViewById(R.id.btnSearchDriverLicence);
		mSearchDriverInfo.setOnClickListener(this);
		mSearchPoliceInfo = (Button) findViewById(R.id.btnSearchPolice);
		mSearchPoliceInfo.setOnClickListener(this);
		mTakePic = (Button) findViewById(R.id.btnTakePic);
		mTakePic.setOnClickListener(this);
		mBtnSignature = (Button) findViewById(R.id.btnSignature);
		mBtnSignature.setOnClickListener(this);
		mBtnSubmit = (Button) findViewById(R.id.btnsubmit);
		mBtnSubmit.setOnClickListener(this);

		etDriverLicenceNo = (EditText) findViewById(R.id.etDriverNo);

		tvPoliceName = (TextView) findViewById(R.id.tvPoliceName);
		tvPoliceName.setText("民警姓名："
				+ LogicManager.policeManager().getcurrentpolice().getName());
		tvPoliceNo = (TextView) findViewById(R.id.tvPoliceNo);
		tvPoliceNo
				.setText("民警警号："
						+ LogicManager.policeManager().getcurrentpolice()
								.getPoliceno());
		tvDriverName = (TextView) findViewById(R.id.tvDriverName);
		tvDriverType = (TextView) findViewById(R.id.tvDriverType);
		tvDriverAge = (TextView) findViewById(R.id.tvDriverAge);

		rbtnSafeDeviceReady = (RadioButton) findViewById(R.id.rbtnsafedeviceready);
		rbtnNoSafeDeviceReady = (RadioButton) findViewById(R.id.rbtnnosafedeviceready);
		rbtnWheelBroken = (RadioButton) findViewById(R.id.rbtnwheelbroken);
		rbtnNoWheelBroken = (RadioButton) findViewById(R.id.rbtnnowheelbroken);
		rbtnYearChecked = (RadioButton) findViewById(R.id.rbtnyearchecked);
		rbtnNoYearChecked = (RadioButton) findViewById(R.id.rbtnnoyearchecked);

		etStart = (EditText) findViewById(R.id.etStart);
		etEnd = (EditText) findViewById(R.id.etEnd);

		etDriverTime = (EditText) findViewById(R.id.etDriverTime);
		etTel = (EditText) findViewById(R.id.etTel);
		etPermittedGoods = (EditText) findViewById(R.id.etPermittedGoods);
		etPermittedWeight = (EditText) findViewById(R.id.etPermittedWeight);
		etRealWeight = (EditText) findViewById(R.id.etRealWeight);
		etSafeMethod = (EditText) findViewById(R.id.etSafeMethod);

	}

	private void setUIWithTrafficInfo() {
		mTrafficInfo.setPoliceid(LogicManager.policeManager()
				.getcurrentpolice().getId());
		tvPlateNumber.setText("车辆号牌:" + mTrafficInfo.getPlatenumber());
		etStart.setText(mTrafficInfo.getStartposition());
		etEnd.setText(mTrafficInfo.getEndposition());

		DriverLicence licence = LogicManager.driverLicenceManager()
				.loadlicenceinfo(mTrafficInfo.getDriverid());
		setDriverUIWithLicence(licence);

		etDriverTime.setText(mTrafficInfo.getDrivertime());
		etTel.setText(mTrafficInfo.getTelnum());
		etPermittedGoods.setText(mTrafficInfo.getPermittedgoods());
		etPermittedWeight
				.setText(mTrafficInfo.getPermittedquality().toString());
		// etRealWeight.setText(mTrafficInfo.getActualquality().toString());
		etSafeMethod.setText(mTrafficInfo.getSavemethod());

		rbtnSafeDeviceReady.setChecked(mTrafficInfo.getIssafedeviceready());
		rbtnNoSafeDeviceReady.setChecked(!mTrafficInfo.getIssafedeviceready());

		rbtnWheelBroken.setChecked(mTrafficInfo.getIswheelbroken());
		rbtnNoWheelBroken.setChecked(!mTrafficInfo.getIswheelbroken());

		rbtnYearChecked.setChecked(mTrafficInfo.getIsyearchecked());
		rbtnNoYearChecked.setChecked(!mTrafficInfo.getIsyearchecked());

	}

	private void setDriverUIWithLicence(DriverLicence licence) {
		etDriverLicenceNo.setText(licence.getLicenceno());
		tvDriverType.setText("驾照类型:" + licence.getType());
		tvDriverAge.setText("驾龄:" + licence.getDriverage().toString());
		tvDriverName.setText("司机姓名:" + licence.getDrivername());
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.btnSearchDriverLicence:
			String licenceno = etDriverLicenceNo.getText().toString();
			if (CheckInputUtil.islicencenoverified(licenceno)) {
				DriverLicence licence = LogicManager.driverLicenceManager()
						.loadlicenceinfo(licenceno);
				if (licence != null) {
					setDriverUIWithLicence(licence);
					mTrafficInfo.setDriverid(licence.getId());
				} else {
					Util.showToast(TrafficActivity.this, "没有该驾照数据，请创建");
					Intent intent = new Intent(TrafficActivity.this,
							AddLicenceActivity.class);
					intent.putExtra(AddLicenceActivity.TAGLICENCENO, licenceno);
					startActivityForResult(intent, REQUESTCODE_ADDLICENCE);
				}
			} else {
				Util.showToast(TrafficActivity.this, "驾照非法");
			}
			break;
		case R.id.btnSearchPolice:
			Intent i = new Intent(TrafficActivity.this,
					ListActivityPoliceInfo.class);
			startActivityForResult(i, REQUESTCODE_SEARCHPOLICE);

			break;
		case R.id.btnTakePic:
			startActivityForResult(new Intent(TrafficActivity.this,
					CaptureActivity.class).putExtra(CaptureActivity.TAGIMGPATH,
					mTrafficInfo.getPic()), REQUESTCODE_CAPTURE);
			break;
		case R.id.btnsubmit:
			submittraffic();
			break;
		case R.id.btnSignature:
			startActivityForResult(new Intent(TrafficActivity.this,
					SignatureActivity.class), REQUESTCODE_SIGNATURE);
		default:
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUESTCODE_ADDLICENCE
				&& resultCode == AddLicenceActivity.RSTADDLICENCE) {
			// 添加驾照成功
			String licenceno = data
					.getStringExtra(AddLicenceActivity.TAGLICENCENO);
			DriverLicence licence = LogicManager.driverLicenceManager()
					.loadlicenceinfo(licenceno);

			setDriverUIWithLicence(licence);

			mTrafficInfo.setDriverid(licence.getId());

		} else if (requestCode == REQUESTCODE_SEARCHPOLICE
				&& resultCode == ListActivityPoliceInfo.RSTSEARCHPOLICE) {
			String policeno = data
					.getStringExtra(ListActivityPoliceInfo.TAGPOLICENO);
			Police police = LogicManager.policeManager().loadpolice(policeno);
			tvPoliceName.setText("民警姓名：" + police.getName());
			tvPoliceNo.setText("民警警号：" + police.getPoliceno());

			mTrafficInfo.setPoliceid(police.getId());
		} else if (requestCode == REQUESTCODE_CAPTURE) {
			String picPath = data.getStringExtra(CaptureActivity.TAGIMGPATH);
			mTrafficInfo.setPic(picPath);
		} else if (requestCode == REQUESTCODE_SIGNATURE) {
			String sigPicPath = data
					.getStringExtra(SignatureActivity.TAGSIGIMGPATH);
			mTrafficInfo.setSig(sigPicPath);
		}
		// else if (requestCode == REQUESTCODE_BUSHISTORY && resultCode ==
		// ListActivityBusInfo.RSTBUSHISTORY) {
		// Long busId = data.getLongExtra(ListActivityBusInfo.TAGBUSID, 0);
		// mTrafficInfo = LogicManager.busManager().loadbusinfo(busId);
		// setUIWithBusInfo();
		// }
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void submittraffic() {
		mTrafficInfo.setStartposition(etStart.getText().toString());
		mTrafficInfo.setEndposition(etEnd.getText().toString());
		mTrafficInfo.setDrivertime(etDriverTime.getText().toString());
		mTrafficInfo.setTelnum(etTel.getText().toString());
		mTrafficInfo.setPermittedgoods(etPermittedGoods.getText().toString());
		mTrafficInfo
				.setPermittedquality(etPermittedWeight.getText().length() == 0 ? null
						: Float.parseFloat(etPermittedWeight.getText()
								.toString()));
		mTrafficInfo
				.setActualquality(etRealWeight.getText().length() == 0 ? null
						: Float.parseFloat(etRealWeight.getText().toString()));
		mTrafficInfo.setCheckdate(new Date());
		mTrafficInfo.setIsyearchecked(rbtnYearChecked.isChecked());
		mTrafficInfo.setIssafedeviceready(rbtnSafeDeviceReady.isChecked());
		mTrafficInfo.setIswheelbroken(rbtnWheelBroken.isChecked());
		mTrafficInfo.setSavemethod(etSafeMethod.getText().toString());
		if (checktraffic()) {
			LogicManager.trafficManager()
					.addtrafficinfo(mTrafficInfo, mHandler);
		}
	}

	private boolean checktraffic() {
		boolean ret = true;

		if (mTrafficInfo.getDriverid() == null) {
			Util.showToast(TrafficActivity.this, "驾照信息错了哦，亲");
			ret = false;
			return ret;
		}
		if (!CheckInputUtil.isbusnoverified(mTrafficInfo.getPlatenumber())) {
			Util.showToast(TrafficActivity.this, "车牌号码号码错了哦，亲");
			ret = false;
			return ret;
		}
		if (mTrafficInfo.getPoliceid() == null) {
			Util.showToast(TrafficActivity.this, "警察信息错了哦，亲");
			ret = false;
			return ret;
		}

		if (mTrafficInfo.getDrivertime() == null
				|| mTrafficInfo.getDrivertime().length() == 0) {
			Util.showToast(TrafficActivity.this, "驾驶时间错了哦，亲");
			ret = false;
			return ret;
		}

		if (mTrafficInfo.getTelnum() == null
				|| mTrafficInfo.getTelnum().length() != 11) {
			Util.showToast(TrafficActivity.this, "电话号码号码错了哦，亲");
			ret = false;
			return ret;
		}

		if (mTrafficInfo.getPermittedgoods() == null) {
			Util.showToast(TrafficActivity.this, "准载货物信息错了哦，亲");
			ret = false;
			return ret;
		}

		if (mTrafficInfo.getActualquality() == null) {
			Util.showToast(TrafficActivity.this, "实载信息错了哦，亲");
			ret = false;
			return ret;
		}

		if (mTrafficInfo.getPermittedquality() == null) {
			Util.showToast(TrafficActivity.this, "核载信息错了哦，亲");
			ret = false;
			return ret;
		}

		if (!CheckInputUtil.isbuspicverified(mTrafficInfo.getPic())) {
			Util.showToast(TrafficActivity.this, "至少拍两张照片哦，亲");
			ret = false;
			return ret;
		}
		if (!CheckInputUtil.issigverified(mTrafficInfo.getSig())) {
			Util.showToast(TrafficActivity.this, "需要签名哦，亲");
			ret = false;
			return ret;
		}
		// 实载人数大于核载人数
		if (mTrafficInfo.getActualquality() > mTrafficInfo
				.getPermittedquality()) {
			Util.showToast(TrafficActivity.this, "超载了哦，亲");
			ret = false;
			return ret;
		}

		if (mTrafficInfo.getSavemethod() == null) {
			Util.showToast(TrafficActivity.this, "施救方法错了哦，亲");
			ret = false;
			return ret;
		}

		return ret;
	}
}
